package com.ruoyi.project.lease.order.controller;

import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.lease.car.domain.Car;
import com.ruoyi.project.lease.car.service.ICarService;
import com.ruoyi.project.lease.customer.domain.Customer;
import com.ruoyi.project.lease.customer.service.ICustomerService;
import com.ruoyi.project.lease.order.domain.Order;
import com.ruoyi.project.lease.order.service.IOrderService;
import com.ruoyi.project.system.user.domain.User;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 客户的订单管理Controller
 *
 * @author admin
 * @date 2022-04-28
 */
@Controller
@RequestMapping("/lease/custorder")
public class CustOrderController extends BaseController {
    private String prefix = "lease/order";

    @Autowired
    private IOrderService orderService;

    @Autowired
    private ICarService carService;

    @Autowired
    private ICustomerService customerService;

    @RequiresPermissions("lease:custorder:view")
    @RequiresRoles("customer")
    @GetMapping()
    public String order()
    {
        return prefix + "/cust_order";
    }

    /**
     * 查询订单管理列表
     */
    @RequiresPermissions("lease:custorder:list")
    @RequiresRoles("customer")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Order order)
    {
        startPage();
        // 获取当前的用户
        User currentUser = ShiroUtils.getSysUser();
        Customer currentCustomer = customerService.selectCustomerByCustPhone(currentUser.getLoginName());
        if (currentCustomer.getCustNo() != null) {
            order.setCustNo(currentCustomer.getCustNo());
            List<Order> list = orderService.selectOrderList(order);
            return getDataTable(list);
        } else {
            List<Order> list = new ArrayList<Order>();
            return getDataTable(list);
        }


    }

    /**
     * 导出订单管理列表
     */
    @RequiresPermissions("lease:custorder:export")
    @RequiresRoles("customer")
    @Log(title = "订单管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Order order)
    {
        List<Order> list = orderService.selectOrderList(order);
        ExcelUtil<Order> util = new ExcelUtil<Order>(Order.class);
        return util.exportExcel(list, "订单管理数据");
    }

    /**
     * 修改订单管理
     */
    @RequiresPermissions("lease:custorder:edit")
    @RequiresRoles("customer")
    @GetMapping("/edit/{orderId}")
    public String edit(@PathVariable("orderId") Long orderId, ModelMap mmap)
    {
        Order order = orderService.selectOrderByOrderId(orderId);
        Car car = carService.selectCarByCarId(order.getCarId());
        Customer customer = customerService.selectCustomerByCustNo(order.getCustNo());
        mmap.put("order", order);
        mmap.put("car", car);
        mmap.put("customer", customer);
        return prefix + "/cust_edit";
    }

    /**
     * 修改保存订单管理
     */
    @RequiresPermissions("lease:custorder:edit")
    @RequiresRoles("customer")
    @Log(title = "订单管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Order order)
    {
        Long date_diff = order.getExpectReturnTime().getTime() - order.getRentTime().getTime();
        Long diffDays = date_diff / (24 * 60 * 60 * 1000);
        // 最少租1天
        if (diffDays < 1L) {
            diffDays = 1L;
        }
        // 预估租车价格和总金额
        Long rentPrice = order.getDayPrice() * diffDays;
        order.setRentPrice(rentPrice);
        order.setAllPrice(rentPrice);
        return toAjax(orderService.updateOrder(order));
    }

    /**
     * 取消订单管理
     */
    @RequiresPermissions("lease:custorder:edit")
    @RequiresRoles("customer")
    @Log(title = "订单管理", businessType = BusinessType.CANCEL)
    @GetMapping( "/cancel/{orderId}/{carId}/{custNo}")
    @ResponseBody
    public AjaxResult cancel(@PathVariable("orderId") Long orderId,
                             @PathVariable("carId") Long carId,
                             @PathVariable("custNo") Long custNo)
    {
        Order order = orderService.selectOrderByOrderId(orderId);
        if (order.getOrderStatus() != 3) {
            return error("该订单不能取消！");
        }
        //将车辆状态设置为 “空闲”
        Car car = carService.selectCarByCarId(carId);
        car.setCarStatus(0);
        carService.updateCar(car);
        //将订单状态设置为 “已取消”
        return toAjax(orderService.changeStatusOrderByOrderId(orderId, 1));
    }

    /**
     * 确认订单
     */
    @RequiresPermissions("lease:custorder:edit")
    @RequiresRoles("customer")
    @Log(title = "订单管理", businessType = BusinessType.CANCEL)
    @GetMapping( "/confirm/{orderId}/{carId}/{custNo}")
    @ResponseBody
    public AjaxResult confirm(@PathVariable("orderId") Long orderId,
                              @PathVariable("carId") Long carId,
                              @PathVariable("custNo") Long custNo)
    {
        Order order = orderService.selectOrderByOrderId(orderId);
        if (order.getDeposit() == 0L) {
            return error("请先编辑订单确认金额！");
        }
        //将车辆状态设置为 “已租出”
        Car car = carService.selectCarByCarId(carId);
        car.setCarStatus(1);
        Long count = car.getCarCount();
        // 车辆租出次数+1
        car.setCarCount(count + 1);
        carService.updateCar(car);
        Customer customer = customerService.selectCustomerByCustNo(custNo);
        // 客户租车次数+1
        Long count2 = customer.getRentCount();
        customer.setRentCount(count2 + 1);
        customerService.updateCustomer(customer);
        // 将订单状态设置为“租出”
        return toAjax(orderService.changeStatusOrderByOrderId(orderId, 0));
    }

    /**
     * 还车
     */
    @RequiresPermissions("lease:custorder:edit")
    @RequiresRoles("customer")
    @GetMapping("/return_car/{orderId}")
    public String returnCar(@PathVariable("orderId") Long orderId, ModelMap mmap)
    {
        Order order = orderService.selectOrderByOrderId(orderId);
        Car car = carService.selectCarByCarId(order.getCarId());
        Customer customer = customerService.selectCustomerByCustNo(order.getCustNo());
        mmap.put("order", order);
        mmap.put("car", car);
        mmap.put("customer", customer);
        return prefix + "/cust_return_car";
    }

    /**
     * 保存还车
     */
    @RequiresPermissions("lease:custorder:edit")
    @RequiresRoles("customer")
    @Log(title = "订单管理", businessType = BusinessType.UPDATE)
    @PostMapping("/return_car")
    @ResponseBody
    public AjaxResult returnCarSave(Order order)
    {
        // 现在归还的时间
        Date nowReturnTime = order.getActualReturnTime();
        // 之前约定还车时间
        Order beforeOrder = orderService.selectOrderByOrderId(order.getOrderId());
        Date beforeReturnTime = order.getExpectReturnTime();
        if (nowReturnTime.getTime() > beforeReturnTime.getTime()) {
            Long date_diff = nowReturnTime.getTime() - beforeReturnTime.getTime();
            Long diffDays = date_diff / (24 * 60 * 60 * 1000);
            if (diffDays >= 1) {
                // 延期大于1天
                order.setDelayPrice(diffDays * order.getDelayDayPrice());
            } else {
                // 延期小于1天
                order.setDelayPrice(diffDays * order.getDelayHourPrice());
            }
        } else {
            order.setDelayPrice(0L);
        }

        Long delayPrice;
        Long damagePrice;
        Long rentPrice;
        if (order.getDelayPrice() == null || order.getDelayPrice() == 0L) {
            delayPrice = 0L;
        } else {
            delayPrice = order.getDelayPrice();
        }
        if (beforeOrder.getRentPrice() == null || beforeOrder.getRentPrice() == 0L) {
            rentPrice = 0L;
        } else {
            rentPrice = beforeOrder.getRentPrice();
        }
        if (order.getDamagePrice() == null || order.getDamagePrice() == 0L) {
            damagePrice = 0L;
        } else {
            damagePrice = order.getDamagePrice();
        }

        // 计算总金额
        order.setAllPrice(delayPrice + rentPrice + damagePrice);

        // 将订单状态设为为“已还车”
        order.setOrderStatus(2);
        // 将车辆状态设为为“空闲”
        Car car = carService.selectCarByCarId(order.getCarId());
        car.setCarStatus(0);
        carService.updateCar(car);
        return toAjax(orderService.updateOrder(order));
    }

    /**
     * 预览订单信息
     */
    @RequiresPermissions("lease:custorder:view")
    @RequiresRoles("customer")
    @GetMapping( "/preview/{orderId}")
    public String preview(@PathVariable("orderId") Long id, ModelMap mmap) {
        Order order = orderService.selectOrderByOrderId(id);
        Car car = carService.selectCarByCarId(order.getCarId());
        Customer customer = customerService.selectCustomerByCustNo(order.getCustNo());
        mmap.put("order", order);
        mmap.put("car", car);
        mmap.put("customer", customer);
        return prefix + "/preview";
    }

}
